import {
  addUserChannelByIdAPI,
  delUserChannelByIdAPI,
  getChannelsAPI,
  getUserChannelAPI,
} from '@/api/channel';
import { ChannelType } from './../reducers/channel';
import { AppDispatch } from '..';
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage';

export const getChannelsAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getChannelsAPI();
    console.log('res: ', res);
    dispatch({ type: 'channel/saveList', payload: res.data.channels });
  };
};

export const getUserChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    // 如果存在token
    if (hasToken()) {
      const res = await getUserChannelAPI();
      dispatch({
        type: 'channel/saveUserList',
        payload: res.data.channels,
      });
      return;
    }
    // 如果不存在token，从缓存取出关注的频道列表
    const localList = getLocalChannels();

    // 缓存中有保存的频道列表，直接存入redux中
    if (localList.length) {
      dispatch({
        type: 'channel/saveUserList',
        payload: localList,
      });
      return;
    }

    // 缓存中没有保存的频道列表，从全部的频道列表中，取出前10个
    const res = await getChannelsAPI();
    const resSlice = res.data.channels.slice(0, 10);
    dispatch({
      type: 'channel/saveUserList',
      payload: resSlice,
    });
    setLocalChannels(resSlice);
  };
};

export const delUserChannelByIdAction = (id: number) => {
  return async (dispatch: AppDispatch) => {
    await delUserChannelByIdAPI(id);
    //  使用id删除redux中的一条数据
    dispatch({
      type: 'channel/delUserChannelById',
      payload: id,
    });
  };
};

export const addUserChannelByIdAction = (newChannel: ChannelType) => {
  return async (dispatch: AppDispatch) => {
    await addUserChannelByIdAPI([newChannel]);
    dispatch({
      type: 'channel/addUserChannel',
      payload: newChannel,
    });
  };
};

export const setChannelIdAction = (id: number) => {
  return {
    type: 'channel/setChannelId',
    payload: id,
  };
};
